<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";
import { initRouter, getTopMenu } from "@/router/utils";
import { REGEXP_PHONE } from "@/views/login/utils/rule";
import { sendBindPhoneCode } from "@/api/sms";
import type { LoginSuccessData, PartialAuthData } from "@/api/user";
import { getToken } from "@/utils/auth";

defineOptions({ name: "WelcomeBindPhone" });

const router = useRouter();
const userStore = useUserStoreHook();

const formRef = ref<FormInstance>();
const loading = ref(false);
const sending = ref(false);
const countdown = ref(0);
let timer: ReturnType<typeof setInterval> | null = null;

const form = reactive({
  phone: "",
  code: ""
});

const OPEN_ID_KEY = "mock_platform_openid";
const TICKET_KEY = "mock_platform_ticket";

const rules = computed<FormRules>(() => ({
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: REGEXP_PHONE, message: "手机号格式不正确", trigger: "blur" }
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}));

const ensurePartialContext = () => {
  if (userStore.partialAction === "need_bind_phone" && userStore.partialToken) {
    return;
  }
  if (userStore.partialAction === "need_verify_identity") {
    router.replace("/welcome/verification");
    return;
  }
  const token = getToken();
  if (token?.accessToken) {
    router.replace("/welcome");
  } else {
    router.replace("/login");
  }
};

const startCountdown = (value: number) => {
  countdown.value = value;
  if (timer) {
    clearInterval(timer);
  }
  timer = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0 && timer) {
      clearInterval(timer);
      timer = null;
    }
  }, 1000);
};

const afterAuthSuccess = async (msg: string) => {
  await initRouter();
  await router.push(getTopMenu(true).path);
  message(msg, { type: "success" });
};

const handleSendCode = async () => {
  if (!REGEXP_PHONE.test(form.phone)) {
    message("请先输入合法的手机号", { type: "warning" });
    return;
  }
  if (!userStore.partialToken) {
    ensurePartialContext();
    return;
  }
  try {
    sending.value = true;
    const res = await sendBindPhoneCode(userStore.partialToken, form.phone);
    if (res.success) {
      startCountdown(res.data?.expires_in ?? 60);
      message("验证码已发送", { type: "success" });
      if (res.data?.debug_code) {
        console.debug("SMS Debug Code", res.data.debug_code);
      }
    }
  } catch (error: any) {
    const msg = error?.message ?? "验证码发送失败";
    message(msg, { type: "error" });
  } finally {
    sending.value = false;
  }
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;
  if (!userStore.partialToken) {
    ensurePartialContext();
    return;
  }

  loading.value = true;
  try {
    const result = await userStore.registerAccount({
      phone: form.phone,
      code: form.code,
      register_channel: "oauth",
      partial_token: userStore.partialToken
    });

    if (result.success && result.data) {
      const payload = result.data as PartialAuthData | LoginSuccessData;
      if ((payload as PartialAuthData).partial) {
        const partial = payload as PartialAuthData;
        if (partial.incompleteAction === "need_verify_identity") {
          router.replace("/welcome/verification");
          return;
        }
        message(partial.context?.message || "请重新获取验证码", {
          type: "error",
          grouping: true
        });
        return;
      }

      const successPayload = payload as LoginSuccessData;

      // 触发平台模拟登录，确保整体流程调用真实接口
      const openId = localStorage.getItem(OPEN_ID_KEY) || "";
      const ticket =
        sessionStorage.getItem(TICKET_KEY) ||
        Math.random().toString(36).slice(2, 10).toUpperCase();
      try {
        const platformRes = await userStore.loginByPlatform({
          ticket,
          nickname: successPayload.profile?.nickname ?? "扫码体验用户",
          avatar: successPayload.profile?.avatar ?? "",
          client: "buyer",
          openid: openId || undefined
        });
        if (!platformRes.success) {
          message(platformRes.msg || "模拟登录失败，请重新扫码", {
            type: "error"
          });
          userStore.SET_PARTIAL("need_bind_phone", null, "", "");
          router.replace("/login");
          return;
        }
      } catch (error: any) {
        message(error?.message ?? "模拟登录失败，请重新扫码", {
          type: "error"
        });
        userStore.SET_PARTIAL("need_bind_phone", null, "", "");
        router.replace("/login");
        return;
      }

      await afterAuthSuccess("手机号绑定成功");
    }
  } catch (error: any) {
    const msg = error?.message ?? "绑定失败";
    message(msg, { type: "error" });
  } finally {
    loading.value = false;
  }
};
const logout = () => {
  useUserStoreHook().logOut();
};
onMounted(() => {
  ensurePartialContext();
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

watch(
  () => userStore.partialAction,
  action => {
    if (action === "need_verify_identity") {
      router.replace("/welcome/verification");
    } else if (action !== "need_bind_phone") {
      ensurePartialContext();
    }
  }
);
</script>

<template>
  <div class="bind-wrapper">
    <el-card class="bind-card">
      <h2 class="title">绑定手机号</h2>
      <p class="subtitle">
        该账号通过第三方创建，需先绑定手机号以便后续通知与认证。验证码发送至您输入的手机号，请注意查收。
      </p>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="bind-form"
        size="large"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            clearable
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="短信验证码" prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码" clearable>
            <template #append>
              <el-button
                type="primary"
                :loading="sending"
                :disabled="countdown > 0 || sending"
                @click="handleSendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : "获取验证码" }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            class="submit-btn"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >
            完成绑定
          </el-button>
        </el-form-item>
      </el-form>

      <el-button link type="primary" class="back-login" @click="logout">
        返回登录
      </el-button>
    </el-card>
  </div>
</template>

<style scoped>
.bind-wrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 16px;
  background: linear-gradient(125deg, #f6f8ff 0%, #ffffff 100%);
}

.bind-card {
  width: 100%;
  max-width: 440px;
  padding: 24px 28px;
  border: none;
  box-shadow: 0 20px 40px rgb(35 84 172 / 12%);
}

.title {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.subtitle {
  margin-bottom: 24px;
  color: #6b7280;
  line-height: 1.7;
  font-size: 14px;
}

.bind-form {
  margin-top: 12px;
}

.submit-btn {
  width: 100%;
}

.back-login {
  margin-top: 8px;
}
</style>
